package com.heima.appGateway.filter;

import com.heima.appGateway.utils.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthenticationFilter implements GlobalFilter , Ordered {

    public static final String TOKEN = "Token";
    public static final String LOGIN_TOKEN = "/user/api/v1/login/login_auth/";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getPath().toString().contains(LOGIN_TOKEN)){
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN);
        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)){
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpResponse response = exchange.getResponse();
//        ServerHttpRequest request = exchange.getRequest();
//        if (request.getPath().toString().contains(LOGIN_TOKEN)){
//            return chain.filter(exchange);
//        }
//        HttpHeaders headers = request.getHeaders();
//        String token = headers.getFirst(TOKEN);
//        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)){
//            response.setComplete();
//        }
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return 0;
//    }

//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//        if (request.getPath().toString().contains(LOGIN_TOKEN)){
//            return chain.filter(exchange);
//        }
//        HttpHeaders headers = request.getHeaders();
//        String token = headers.getFirst(TOKEN);
//        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)){
//            response.setComplete();
//        }
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return 0;
//    }
}
